//模块化接口
var app = getApp()
var Util = require('../../utils/util.js')

//登录
function logIn(that, initFunction){
    var that = that
    var LogIn = this
    var requestInfo = that.data.requestInfo
    //获取缓存中的的token_id
    var token_id = wx.getStorageSync('token_id')
    requestInfo.token_id = token_id
    that.setData({
        requestInfo: requestInfo
    })

    //验证登录状态是否有效
    wx.checkSession({
      success: function (res) {
        //如果token_id 不存在，重新登录
        if (token_id.length == 0) {
          LogIn.reLogIn(that, initFunction)
        }
        else{
          initFunction()
        }
      },
      fail: function () {
        LogIn.reLogIn(that, initFunction)
      }
    })


}

//重新登录
function reLogIn(that, initFunction){
    var that = that
    var LogIn = this
    wx.login({
      success: function (res){
        LogIn.getWxInfo(that, res, initFunction)
        }
    })
}

//调用接口wx.getUserInfo, 获取用户部分个人信息
function getWxInfo(that, res, initFunction){
    var that = that
    var LogIn = this
    var requestInfo = that.data.requestInfo
    var logInRequestInfo = {}
    logInRequestInfo.code = res.code
    wx.getUserInfo({
        success: function(res){
            //获取（1）加密数据；（2）原始数据；（3）签名验证； （4）加密初始向量
            logInRequestInfo.encryptedData = res.encryptedData
            logInRequestInfo.rawData = res.rawData
            logInRequestInfo.signature = res.signature
            logInRequestInfo.iv = res.iv
            //第三步， 调用接口loginWithWechat，传参到后台服务器
            app.wechatLogin(function(callBackInfo){
                if(callBackInfo.status == 'SUCCESS'){
                    wx.setStorageSync('token_id', callBackInfo.data)
                    requestInfo.token_id = callBackInfo.data
                    that.setData({
                        requestInfo: requestInfo
                    })
                    initFunction()
                }
            }, logInRequestInfo)   
        }
    })
}

module.exports = {  
  logIn: logIn,
  reLogIn: reLogIn,  
  getWxInfo: getWxInfo,
}